import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import joblib

# 数据加载
data = pd.read_csv('手写数字识别.csv')

# 数据处理(可视化,特征工程)
x = data.iloc[:,1:]/255.
y = data.iloc[:,0]
# print(Counter(y))
# print(x.shape)
# digit =x.iloc[999].values.reshape(28,28)
# # print(digit)
# plt.imshow(digit,cmap='gray')
# plt.show()
# print(y.iloc[999])

# x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,stratify=y,random_state=22)
# # 模型训练
# knn =KNeighborsClassifier(n_neighbors=3)
# knn.fit(x_train,y_train)
#
# # 模型评估与预测
# print(knn.score(x_test, y_test))
#
# # 模型保存
# joblib.dump(knn,'knn.pth')


# 加载模型进行预测
img = plt.imread('demo.png')
# plt.imshow(img,cmap='gray')
# plt.show()
model = joblib.load('knn.pth')
print(model.predict(img.reshape(1, -1)))